from PIL import Image
import torchvision.transforms as transforms

import numpy as np

def clip_1_99(img):
    def get_count(img):
        count = np.zeros([256])
        for i in img.reshape(-1):
            count[int(i)]+=1
        return count
    def presum(count):
        sum = count.copy()
        for i in range(1,sum.size):
            sum[i]+=sum[i-1]
        sum = sum/sum[-1]
        # plt.bar(range(0,256),sum)
        # print(sum)
        min_ = sum.searchsorted(0.01)
        max_ = sum.searchsorted(0.99)
        return (min_,max_)
    count = get_count(img)
    min_,max_ = presum(count)
    return img.clip(min_,max_)

def color_0_255(img,esp = 0):
    min_ = img.min()
    max_ = img.max()
    img_norm = (img-min_)/(max_-min_)*255
    return img_norm

def img_pad_to_square(img):
    """
    
    """
    _,h,w = img.size

    # 横竖均可
    pad_lr = max(0,w-h)
    pad_left = pad_lr//2
    pad_right = pad_lr//2+pad_lr%2
    pad_td = max(0,h-w)
    pad_top = pad_td//2
    pad_bottom = pad_td//2+pad_td%2
    pad = (pad_top,pad_left,pad_bottom,pad_right)


    img_pad = transforms.Pad(pad,fill=(255,255,255),padding_mode='constant')(img)

    pad_i = int(w*0.1)
    pad2 = [pad_i]*4
    img_pad2 = transforms.Pad(pad2,fill=(255,255,255),padding_mode='constant')(img_pad)
    return img_pad2